package com.ysjr.anipluginsapp.manager;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;

/**
 * -----------------------------------
 * (☆^ー^☆)
 *
 * @author : Ani_aierJun
 * github: https://github.com/aierjun
 * email: aierjun@qq.com
 * create in : 11:39 2019/5/7
 * -----------------------------------
 */


public class PluginsManager {

    private DexClassLoader dexClassLoader;
    private Resources resources;
    private Context context;
    private String entryActivityName;

    private static final PluginsManager ourInstance = new PluginsManager();
    public static PluginsManager getInstance(){
        return ourInstance;
    }

    public PluginsManager(){

    }

    public void Attach(Context context){
        this.context = context.getApplicationContext();
    }

    public void loadPath(String path){
        File dexOutFile = context.getDir("dex",Context.MODE_PRIVATE);
        dexClassLoader = new DexClassLoader(path,dexOutFile.getAbsolutePath(),null,context.getClassLoader());

        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageArchiveInfo(path,PackageManager.GET_ACTIVITIES);
            entryActivityName = packageInfo.activities[0].name;

            AssetManager  assetManager = AssetManager.class.newInstance();

            Method addAssetPath = AssetManager.class.getMethod("addAssetPath",String.class);
            addAssetPath.invoke(assetManager,path);

            resources = new Resources(assetManager,context.getResources().getDisplayMetrics(),context.getResources().getConfiguration());

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public DexClassLoader getDexClassLoader(){
        return dexClassLoader;
    }

    public Resources getResources(){
        return resources;
    }

    public String getEntryActivityName() {
        return entryActivityName;
    }

}
